package com.amoyt.project.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 跨域访问配置，为前端访问做铺垫
 * 注意：Spring MVC 的跨域配置：作用于 MVC 层面，而Security的跨域是作用于Filter的
 */
@Configuration
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE) // 最高优先级，确保在Security过滤器之前执行
public class CorsConfig {

    // CorsConfigurationSource配置源，用于Security Filter 拦截
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return source;
    }

    // 保留 CorsFilter 作为双重保障
    @Bean
    public CorsFilter corsFilter() {
        return new CorsFilter(corsConfigurationSource());
    }

    private CorsConfiguration buildConfig(){
        log.info("CorsConfig.buildConfig():跨域配置ing...");
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        //1.sessionId多次访问一致,允许携带Cookie
        corsConfiguration.setAllowCredentials(true);

        //2.允许访问的客户端域名或者请求源
        List<String> allowedOriginPatterns = new ArrayList<>();
        allowedOriginPatterns.add("*");
//        allowedOriginPatterns.add("http://localhost:5173");
        corsConfiguration.setAllowedOriginPatterns(allowedOriginPatterns);

        //3.允许任何头
        corsConfiguration.addAllowedHeader("*");

        //4.允许任何方法(post、get等)
//        corsConfiguration.addAllowedMethod("*");
        // 允许的请求方法（明确列出，避免通配符可能的兼容问题）
        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));

        //5.预检请求缓存时间（减少OPTIONS请求次数）
        corsConfiguration.setMaxAge(3600L);

        return corsConfiguration;
    }
}
